//
//  HFCalendarHelper.m
//  HFCalendar
//
//  Created by Luffy on 2021/8/24.
//

#import "HFCalendarHelper.h"
#import "HFCalendarModel.h"

@implementation HFCalendarHelper {
    NSCalendar *_calendar;
}

+ (instancetype)defaultManager {
    static HFCalendarHelper *instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    
    return instance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.customDateStartDate = @"1970年01月01日";
        self.customDateEndDate = [self.yearMonthAndDayFormatter stringFromDate:[NSDate date]];
    }
    return self;
}

- (NSCalendar *)calendar {
    if(!_calendar) {
#ifdef __IPHONE_8_0
        _calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
#else
        _calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
#endif
        _calendar.timeZone = [NSTimeZone localTimeZone];
        _calendar.locale = [NSLocale currentLocale];
    }
    return _calendar;
}

- (NSDateFormatter *)yearFormatter {
    return [[self class] createFormatterWithDateFormat:@"yyyy年"];
}

- (NSDateFormatter *)yearAndMonthFormatter {
    return [[self class] createFormatterWithDateFormat:@"yyyy年MM月"];
}

- (NSDateFormatter *)yearMonthAndDayFormatter {
    return [[self class] createFormatterWithDateFormat:@"yyyy年MM月dd日"];
}

- (HFDateWithTodayType)whetherForTodayWithIndexPath:(NSIndexPath *)indexPath model:(HFCalendarModel *)model {
    // 今天
    NSDateFormatter *formatter = self.yearMonthAndDayFormatter;
    // 获取当前Cell上表示的天数
    NSString *dayString = [NSString stringWithFormat:@"%@%ld日",model.headerTitle,(long)(indexPath.item - (model.firstDayOfTheMonth - 2))];
    NSDate *dayDate = [formatter dateFromString:dayString];
    
    if (dayDate) {
        if ([self date:[NSDate date] isTheSameDateThan:dayDate]) {
            return HFDateEqualToToday;
        } else if ([dayDate compare:[NSDate date]] == NSOrderedDescending) {
            return HFDateLaterThanToday;
        } else {
            return HFDateEarlierThanToday;
        }
    }
    return NO;
}

- (BOOL)date:(NSDate *)date isTheSameDateThan:(NSDate *)otherDate {
    NSDateComponents *components = [self.calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
    NSDateComponents *otherComponents = [self.calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:otherDate];
    return components.year == otherComponents.year && components.month == otherComponents.month && components.day == otherComponents.day;
}

+ (NSDateFormatter *)createFormatterWithDateFormat:(NSString *)dateFormat {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = dateFormat;
    return formatter;
}

@end
